﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;

namespace Common
{

    public class Utility
    {
        public static Bitmap CaptureWindow(AppWindow window)
        {
            window.BringWindowToFront();
            Rectangle rect = window.Rect;
            var capture = new Bitmap(rect.Width, rect.Height);
            using (var g = Graphics.FromImage(capture))
            {
                g.CopyFromScreen(rect.X, rect.Y, 0, 0, rect.Size);
            }
            return capture;
        }
        public static AppWindow FindWindow(string title)
        {
            List<AppWindow> windows = AppWindow.GetWindows();
            foreach (AppWindow window in windows)
            {
                if (window.Title.Contains(title))
                {
                    return window;
                }
            }
            return null;
        }
        public static int GetRegionHash(Bitmap bmp, Rectangle rect)
        {
            BitmapData bData = bmp.LockBits(new Rectangle(new Point(0, 0), bmp.Size), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
            int hash = 0;
            for (int y = 0; y < rect.Height; y++)
            {
                for (int x = 0; x < rect.Width; x++)
                {
                    int color = Marshal.ReadInt32(bData.Scan0, (y + rect.Y) * bData.Stride + (x + rect.X) * 4);
                    hash += color;
                }
            }
            bmp.UnlockBits(bData);
            return hash;
        }
        public static long GetFrontHash(Bitmap bmp, Rectangle rect,int frontColor)
        {
            BitmapData bData = bmp.LockBits(new Rectangle(new Point(0, 0), bmp.Size), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
            long hash = 1;
            for (int y = 0; y < rect.Height; y++)
            {
                for (int x = 0; x < rect.Width; x++)
                {
                    int color = Marshal.ReadInt32(bData.Scan0, (y + rect.Y) * bData.Stride + (x + rect.X) * 4);
                    if(frontColor == color)
                        hash *= (x+2);
                }
            }
            bmp.UnlockBits(bData);
            return hash;
        }
        public static Bitmap GetRegion(Bitmap bmp,Rectangle rect)
        {
            Bitmap image = new Bitmap(rect.Width, rect.Height);
            using (Graphics g = Graphics.FromImage(image))
            {

                g.DrawImage(bmp, 0, 0, rect, GraphicsUnit.Pixel);
            }
            return image;
        }
    }
}
